import {TripService} from "../../service/trip";
import {formatDuration, formatFee} from "../../utils/util";
import {ProfileService} from "../../service/profile";

interface Trip {
    id: string
    start: string
    end: string
    duration: string
    fee: string
    distance: string
    status: string
}

interface MainItem {
    id: string
    navId: string
    data: Trip
}

interface NavItem {
    id: string
    mainID: string
    label: string
}

const licStatusMap = [
    "未认证",
    "未认证",
    "已认证",
]

interface MainItemQueryResult {
    id: string
    top: number
    dataset: {
        navId: string
        navScrollId: string
    }
}


const tripStatusMap = new Map([
    [1, '进行中'],
    [2, '已完成'],
])
Page({

    /**
     * 页面的初始数据
     */
    layoutReady: null as null | undefined | any,
    scrollStates: {
        mainItems: [] as MainItemQueryResult[],
    },

    data: {
        avatarUrl: '',
        indicatorDots: true,
        autopPlay: true,
        interval: 3000,
        duration: 500,
        circular: true,
        multipleItems: 1,
        previousMargin: '',
        nextMargin: '',
        vertical: false,
        imgUrls: [
            "https://img.mukewang.com/6308331b00014fe017920764.jpg",
            "https://img2.mukewang.com/630882330001155417920764.jpg",
            "https://img2.mukewang.com/6306edd30001575217920764.jpg",
            "https://img2.mukewang.com/630882330001155417920764.jpg"
        ],
        tripsHeight: 0,
        scrollTop: 0,
        scrollInfoView: '',
        mainItems: [] as MainItem[],
        navItems: [] as NavItem[],
        navScroll: '',
        navCount: 0,
        navSel: '',
        licStatus: licStatusMap[0],
    },
    populateTrips(trips: any) {
        const mainItems: MainItem[] = []
        const navItems: NavItem[] = []
        let navSel = ''
        let prevNav = ''
        for (let i = 0; i < trips.length; i++) {
            const trip = trips[i]
            const mainId = 'main-' + i
            const navId = 'nav-' + i
            const shortId = trip.id?.substr(trip.id.length-6)
            if (!prevNav) {
                prevNav = navId
            }
            const tripData: Trip = {
                id: trip.id!,
                // @ts-ignore
                shortId: '****'+shortId,
                start: trip.trip?.start?.poi_name||'未知',
                end: trip.trip?.end?.poi_name||'未知',
                distance: '',
                duration: '',
                fee: '',
                status: tripStatusMap.get(trip.trip?.status!)||'未知',
                inProgress: trip.trip?.status ===  2,
            }
            const end = trip.trip?.end
            if (end) {
                tripData.end = end.poi_name||'未知',
                    tripData.distance = end.km_driven?.toFixed(1)+'公里',
                    tripData.fee = formatFee(end.fee_cent||0)
                const dur = formatDuration((end.timestamp_sec||0) - (trip.trip?.start?.timestamp_sec||0))
                tripData.duration = `${dur.hh}时${dur.mm}分`
            }
            mainItems.push({
                id: mainId,
                navId: navId,
                // @ts-ignore
                navScrollId: prevNav,
                data: tripData,
            })
            navItems.push({
                id: navId,
                // @ts-ignore
                mainId: mainId,
                label: shortId||'',
            })
            if (i === 0) {
                navSel = navId
            }
            prevNav = navId
        }
        for (let i = 0; i < this.data.navCount-1; i++) {
            navItems.push({
                id: '',
                // @ts-ignore
                mainId: '',
                label: '',
            })
        }

        this.setData({
            mainItems,
            navItems,
            navSel,
        }, () => {
            this.prepareScrollStates()
        })
    },
    prepareScrollStates() {
        wx.createSelectorQuery().selectAll('.main-item')
            .fields({
                id: true,
                dataset: true,
                rect: true,
            }).exec(res => {
            this.scrollStates.mainItems = res[0]
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad() {

        // const layoutReady = new Promise((resolve)=>{
        //     this.layoutReady = resolve
        // })
        // Promise.all([TripService.GetTrips(2), layoutReady]).then((res) => {
        //     console.log(res)
        // })
        const res = await TripService.GetTrips(2)
        this.populateTrips(res.trips.reverse())

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        wx.createSelectorQuery().select("#heading")
            .boundingClientRect(() => {
                const heigth = wx.getSystemInfoSync().screenHeight - 320
                this.setData({
                    tripsHeight: heigth,
                    navCount: Math.round((heigth / 50))
                })
            }).exec()
    },
    onNavItemTap(e: any) {
        const mainId: string = e.currentTarget?.dataset?.mainId
        const nacId: string = e.currentTarget?.dataset?.itemId
        if (mainId) {
            this.setData({
                navScroll: mainId,
                navSel: nacId
            })
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        const avatarUrl = wx.getStorageSync("avatarUrl")
        if (avatarUrl) {
            this.setData({
                avatarUrl: avatarUrl
            })
        }

        ProfileService.getProfile().then(p=>{
            this.setData({
                licStatus: licStatusMap[p.identity_Status || 0]
            })
        })
    },
    onGetUserInfo() {
        wx.getUserProfile({
            desc: '实时展示您到头像',
            success: (res: { userInfo: { avatarUrl: any } }) => {
                this.setData({
                    avatarUrl: res.userInfo.avatarUrl
                })
                wx.setStorageSync("avatarUrl", res.userInfo.avatarUrl)
            },
            fail: () => [
                wx.showToast({
                    icon: "none",
                    title: "获取头像失败"
                })
            ]
        })
    },

    onRegisterTap() {
        wx.navigateTo({
            url: "/pages/register/register"
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})